package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.controller.utils.RedisUtil;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.UserRegisterDTO;
import com.sky.entity.User;
import com.sky.enumeration.EmailType;
import com.sky.exception.BaseException;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.IEmailService;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/user")
@Api(tags = "C端用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private IEmailService emailService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录:{}", userLoginDTO);
        User user = userService.Login(userLoginDTO);
        // 生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(jwt)
                .email(user.getEmail())
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册:{}", userRegisterDTO);
        if(userRegisterDTO != null && "".equals(userRegisterDTO.getEmail())) {
            throw new BaseException("邮箱不能为空");
        }
        String code = redisUtil.getString(userRegisterDTO.getEmail());
        if("".equals(userRegisterDTO.getCode())) {
            throw new BaseException("验证码不能为空");
        }
        if(!userRegisterDTO.getCode().equals(code)) {
            throw new BaseException("验证码不存在或者不正确");
        }
        userService.register(userRegisterDTO);
        return Result.success();
    }

    /**
     * 获取验证码
     * @param email
     * @return
     */
    @GetMapping("/code")
    @ApiOperation("获取验证码")
    public Result code(String email) {
        log.info("获取验证码:{}", email);
        String hadCode = redisUtil.getString(email);
        if(hadCode !=  null) {
            throw new BaseException("验证码已发出，两分钟后再重试");
        }
        Context context = new Context();
        String code = generated();
        redisUtil.set(email, code,2, TimeUnit.MINUTES);
        context.setVariable("verifyCode", code.toCharArray());
        String content = templateEngine.process(EmailType.EMAIL_TYPE_100.getEmailEngine(), context);
        emailService.sendHtml(EmailType.EMAIL_TYPE_100, email, "\uD83D\uDD28 MeetFood \uD83D\uDD28", content);
        return Result.success();
    }

    private String generated() {
        String str="ABCDEFGHIJKLMNOBQRSTUVWXYZ0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(36));
            sb.append(ch);
        }
        return sb.toString();
    }
}
